<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Category;
use App\Archive;
class CategoryController extends Controller
{
    function __construct(Request $request){
        $this->admin = $request->session()->get('admin', false);
        $this->data = ['admin' => $this->admin,
        			'categorys' => Category::all(),
        			];
    }
    public function index(){
    	$categorys = Category::latest()->paginate(10);
        $this->data['categorys'] =$categorys;
    	return view('blog.categorys',$this->data);
    }
    public function show($id){
    	$archives = Archive::where('category_id',$id)->latest()->paginate(10);
        $this->data['archives'] =$archives;
    	return view('blog.archives',$this->data);
    }
    public function create(){
        if (!$this->admin){ return '小样，你不是主人！';}
    	return view('blog.categoryCreate',$this->data);
    }
    public function edit($id){
        if (!$this->admin){ return '小样，你不是主人！';}
    	$category = Category::findorFail($id);
        $this->data['category'] =$category;
    	return view('blog.categoryEdit',$this->data);
    }
    public function store(Request $request){
        if (!$this->admin){ return '小样，你不是主人！';}
    	$input = $request->all();
    	$input['category_name'] = trim($input['category_name']);
        if (empty(trim($input['category_name'])) || empty($input['category_name'])){
            return '说好的分类名称呢？';
        }
    	Category::create($input);
    	return redirect('/category');
    }
    public function update(Request $request){
    	$input = $request->all();
    	$id = $input['category_id'];
    	$category = Category::findorFail($id);
    	$update = ['category_name'=>trim($input['category_name'])];
    	$category->update($update);
    	return redirect('/category');
    }
    public function delete($id){
        if (!$this->admin){ return '小样，你不是主人！';}
        if (Archive::where('category_id',$id)->first()){
        	return '有文章的分类，删不掉！';
        }
        $category = Category::findorFail($id);
        $category->delete();
        return redirect('/category');
    }
}
